import { BrowserWindowConstructorOptions, contextBridge, ipcRenderer } from 'electron'
import { electronAPI } from '@electron-toolkit/preload'

export interface WindowAPI {
  onAppQuit: () => void
  onMaximize: () => void
  onMinimize: () => void
  showHomeWindow: () => void
  createWindow: (options: { url: string; options?: BrowserWindowConstructorOptions }) => void
  initSocket: <A, B, C, D>(options: {
    userId: string
    getMessageUserList: (data: A[]) => void
    getNewMessage: (data: B) => void
    getUserApproveList: (data: C[]) => void
    getNewUserApprove: (data: C) => void
    getNewUser: (data: D) => void
  }) => void
}

// Custom APIs for renderer
const api: WindowAPI = {
  onAppQuit: (): void => ipcRenderer.send('onAppQuit'),
  onMaximize: (): void => ipcRenderer.send('onMaximize'),
  onMinimize: (): void => ipcRenderer.send('onMinimize'),
  showHomeWindow: (): void => ipcRenderer.send('showHomeWindow'),
  createWindow: (options): void => ipcRenderer.send('createWindow', options),
  initSocket: (options): void => {
    ipcRenderer.send('initSocket', options.userId)
    ipcRenderer.on('messageUserList', (_event, data) => {
      options.getMessageUserList(data)
    })
    ipcRenderer.on('getNewMessage', (_event, data) => {
      options.getNewMessage(data)
    })
    ipcRenderer.on('getUserApproveList', (_event, data) => {
      options.getUserApproveList(data)
    })
    ipcRenderer.on('getNewUserApprove', (_event, data) => {
      options.getNewUserApprove(data)
    })
    ipcRenderer.on('getNewUser', (_event, data) => {
      options.getNewUser(data)
    })
  }
}

// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
// just add to the DOM global.
if (process.contextIsolated) {
  try {
    contextBridge.exposeInMainWorld('electron', electronAPI)
    contextBridge.exposeInMainWorld('api', api)
  } catch (error) {
    console.error(error)
  }
} else {
  // @ts-ignore (define in dts)
  window.electron = electronAPI
  // @ts-ignore (define in dts)
  window.api = api
}
